<script setup>
  import { ref, reactive, computed, onMounted, nextTick, watch } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import useUserStore from '@/stores/user'
  const userStore = useUserStore()

  // 分页相关数据
  const currentPage = ref(1)
  const pageSize = ref(5)
  const size = ref('small')
  const disabled = ref(true)
  const background = ref(true)
  const total = ref(0)
  const loading = ref(false)
  // 权限分配相关状态
  const drawerVisible = ref(false)
  const rolePermissions = ref([]) // 当前角色拥有的权限
  const currentRoleId = ref(null) // 当前操作的角色ID
  const currentRoleName = ref('') // 当前操作的角色名称
  const treeRef = ref(null) // 树形控件引用
  // 监听drawerVisible变化，确保在打开时正确设置权限
  watch(() => drawerVisible.value, (newValue) => {
    if (newValue && treeRef.value && currentRoleId.value) {
      // 等待下一帧确保组件已渲染
      nextTick(() => {
        // 强制重置树的选中状态
        if (treeRef.value) {
          treeRef.value.setCheckedKeys([])
          // 重新设置当前角色的权限
          const permissions = userStore.getRolePermissions(currentRoleId.value) || []
          rolePermissions.value = [...permissions]
          treeRef.value.setCheckedKeys(rolePermissions.value)
        }
      })
    }
  })
  // 处理分配权限
  const handleAssignPermission = (role) => {
    currentRoleId.value = role.roleId
    currentRoleName.value = role.roleName

    // 获取角色已有的权限
    const permissions = userStore.getRolePermissions(role.roleId) || []
    // 强制创建新数组，彻底避免引用共享
    rolePermissions.value = JSON.parse(JSON.stringify(permissions))

    // 先设置权限数据，再打开抽屉
    drawerVisible.value = true
  }

  // 处理权限勾选变化
  const handleCheckChange = (data, checked, indeterminate) => {
    // 使用el-tree提供的方法获取所有选中的节点ID
    if (treeRef.value) {
      const checkedKeys = treeRef.value.getCheckedKeys(false)
      // 强制创建新数组
      rolePermissions.value = [...checkedKeys]
    }
  }

  // 处理权限分配确认
  const handlePermissionConfirm = () => {
    loading.value = true
    setTimeout(() => {
      // 强制创建新数组，避免引用共享
      const success = userStore.updateRolePermissions(currentRoleId.value, [...rolePermissions.value])
      if (success) {
        ElMessage.success(`已成功为角色 ${currentRoleName.value} 分配权限`)
      } else {
        ElMessage.error('权限分配失败，请重试')
      }
      // 关闭抽屉前重置当前角色ID
      drawerVisible.value = false
      currentRoleId.value = null
      loading.value = false
    }, 500)
  }
  // 递归转换路由数据为树形组件所需格式
  const transformMenuToTree = (menuItems) => {
    // 先过滤再转换，避免重复过滤
    const visibleItems = menuItems.filter(item => !item.meta?.hidden)
    return visibleItems.map(item => {
      const treeNode = {
        id: item.path,
        label: item.meta.title,
        icon: item.meta.icon,
      }

      // 递归处理子菜单
      if (item.children && item.children.length > 0) {
        const visibleChildren = item.children.filter(child => !child.meta?.hidden)
        if (visibleChildren.length > 0) {
          treeNode.children = transformMenuToTree(visibleChildren)
        }
      }

      return treeNode
    })
  }

  // 过滤出可见的菜单路由用于权限分配
  const visibleMenuRoutes = computed(() => {
    return transformMenuToTree(userStore.menuRoutes)
  })



  // 搜索表单数据
  const searchForm = reactive({
    roleName: ''
  })

  // 搜索结果数据（用于点击搜索后显示结果）
  const searchResults = ref([])
  const isSearching = ref(false)

  // 选中的角色列表
  const selectedRoles = ref([])

  // 编辑和添加角色的对话框
  const dialogVisible = ref(false)
  const dialogTitle = ref('添加角色')
  const isEdit = ref(false)

  // 角色表单数据
  const roleForm = reactive({
    roleId: '',
    roleName: '',
  })

  // 角色表单校验规则
  const rules = reactive({
    roleName: [
      { required: true, message: '请输入角色名称', trigger: 'blur' }
    ],
  })

  // 角色表单引用
  const roleFormRef = ref(null)



  // 初始化数据
  onMounted(() => {
    total.value = userStore.roleList.length
  })

  // 计算当前页显示的角色列表
  const currentPageRoles = computed(() => {
    // 根据是否处于搜索状态决定使用哪个数据源
    const sourceData = isSearching.value ? searchResults.value : userStore.roleList
    total.value = sourceData.length

    // 计算分页数据
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    return sourceData.slice(start, end)
  })

  // 处理搜索
  const handleSearch = () => {
    if (!searchForm.roleName.trim()) {
      ElMessage.warning('请输入搜索内容')
      return
    }

    loading.value = true

    // 模拟异步搜索过程
    setTimeout(() => {
      searchResults.value = userStore.roleList.filter(role =>
        role.roleName.includes(searchForm.roleName.trim())
      )
      isSearching.value = true
      currentPage.value = 1

      if (searchResults.value.length === 0) {
        ElMessage.info('没有找到匹配的角色')
      } else {
        ElMessage.success(`找到 ${searchResults.value.length} 个匹配的角色`)
      }

      loading.value = false
    }, 300)
  }

  // 处理重置
  const handleReset = () => {
    searchForm.roleName = ''
    isSearching.value = false
    currentPage.value = 1
    selectedRoles.value = []
    disabled.value = true
  }

  // 处理添加角色
  const handleAddRole = () => {
    dialogTitle.value = '添加角色'
    isEdit.value = false
    Object.assign(roleForm, {
      roleId: '',
      roleName: '',
    })
    dialogVisible.value = true
  }

  // 处理编辑角色
  const handleEditRole = (role) => {
    dialogTitle.value = '编辑角色'
    isEdit.value = true
    Object.assign(roleForm, {
      roleId: role.roleId,
      roleName: role.roleName,
    })
    dialogVisible.value = true
  }

  // 处理删除角色
  const handleDeleteRole = (roleId) => {
    // 显示确认对话框
    ElMessageBox.confirm('确定要删除该角色吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      loading.value = true

      // 模拟异步删除过程
      setTimeout(() => {
        // 删除角色
        const index = userStore.roleList.findIndex(role => role.roleId === roleId)
        if (index !== -1) {
          userStore.roleList.splice(index, 1)
        }

        // 如果正在搜索，同步更新搜索结果
        if (isSearching.value) {
          const searchIndex = searchResults.value.findIndex(role => role.roleId === roleId)
          if (searchIndex !== -1) {
            searchResults.value.splice(searchIndex, 1)
          }
        }

        // 如果删除了当前页的最后一条数据，自动回退到上一页
        if (currentPageRoles.value.length === 0 && currentPage.value > 1) {
          currentPage.value--
        }

        ElMessage.success('角色删除成功')

        // 清空选中状态
        selectedRoles.value = []
        disabled.value = true
        loading.value = false
      }, 500)
    }).catch(() => {
      // 用户取消删除
      ElMessage.info('已取消删除')
    })
  }

  // 处理批量删除
  const handleBatchDelete = () => {
    if (selectedRoles.value.length === 0) {
      ElMessage.warning('请选择要删除的角色')
      return
    }

    ElMessageBox.confirm(`确定要删除选中的 ${selectedRoles.value.length} 个角色吗？`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      loading.value = true

      // 模拟异步删除过程
      setTimeout(() => {
        // 批量删除角色
        userStore.roleList = userStore.roleList.filter(role => !selectedRoles.value.includes(role.roleId))

        // 如果正在搜索，同步更新搜索结果
        if (isSearching.value) {
          searchResults.value = searchResults.value.filter(role =>
            !selectedRoles.value.includes(role.roleId)
          )
        }

        // 如果删除了当前页的所有数据，自动回退到上一页
        if (currentPageRoles.value.length === 0 && currentPage.value > 1) {
          currentPage.value--
        }

        // 清空选中状态
        selectedRoles.value = []
        disabled.value = true

        ElMessage.success(`成功删除 ${selectedRoles.value.length} 个角色`)
        loading.value = false
      }, 500)
    }).catch(() => {
      ElMessage.info('已取消删除')
    })
  }

  // 处理选择角色变化
  const handleSelectionChange = (selection) => {
    selectedRoles.value = selection.map(role => role.roleId)
    disabled.value = selectedRoles.value.length === 0
  }

  // 处理表单提交
  const handleSubmit = async () => {
    try {
      // 验证表单
      if (!roleForm.roleName.trim()) {
        ElMessage.error('请输入角色名称')
        return
      }

      loading.value = true

      // 模拟异步提交过程
      setTimeout(() => {
        const now = new Date().toLocaleString('zh-CN')

        if (isEdit.value) {
          // 编辑角色
          // 检查角色名称是否已存在（排除当前编辑的角色）
          const nameExists = userStore.roleList.some(role =>
            role.roleName === roleForm.roleName && role.roleId !== roleForm.roleId
          )
          if (nameExists) {
            ElMessage.error('角色名称已存在')
            loading.value = false
            return
          }

          const index = userStore.roleList.findIndex(role => role.roleId === roleForm.roleId)
          if (index !== -1) {
            userStore.roleList[index] = {
              ...userStore.roleList[index],
              roleName: roleForm.roleName,
              updateTime: now
            }

            // 如果正在搜索，同步更新搜索结果
            if (isSearching.value) {
              const searchIndex = searchResults.value.findIndex(role => role.roleId === roleForm.roleId)
              if (searchIndex !== -1) {
                searchResults.value[searchIndex] = { ...userStore.roleList[index] }
              }
            }

            ElMessage.success('角色更新成功')
          }
        } else {
          // 添加角色
          // 检查角色名称是否已存在
          const nameExists = userStore.roleList.some(role => role.roleName === roleForm.roleName)
          if (nameExists) {
            ElMessage.error('角色名称已存在')
            loading.value = false
            return
          }

          const newRole = {
            roleId: Date.now(), // 使用时间戳作为临时ID
            roleName: roleForm.roleName,
            createTime: now,
            updateTime: now
          }

          // 添加角色到列表末尾
          userStore.roleList.push(newRole)

          // 如果正在搜索，且新角色符合搜索条件，添加到搜索结果末尾
          if (isSearching.value && (newRole.roleName.includes(searchForm.roleName.trim()))) {
            searchResults.value.push(newRole)
          }

          // 切换到最后一页以显示新添加的角色
          const totalPages = Math.ceil(total.value / pageSize.value)
          currentPage.value = totalPages

          ElMessage.success('角色添加成功')
        }

        // 关闭对话框
        dialogVisible.value = false
        loading.value = false
      }, 500)
    } catch (error) {
      // 表单校验失败
      console.error('表单校验失败:', error)
      loading.value = false
    }
  }

  // 处理对话框关闭
  const handleDialogClose = () => {
    dialogVisible.value = false
  }

  // 处理页码变化
  const handleCurrentChange = (val) => {
    currentPage.value = val
  }

  // 处理每页条数变化
  const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1
  }



</script>

<template>
  <div>
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form
        :inline="true"
        :model="searchForm"
        size="small"
      >
        <el-form-item label="角色名称">
          <el-input
            v-model="searchForm.roleName"
            placeholder="请输入角色名称"
            style="width: 240px;"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="handleSearch"
            :loading="loading"
          >
            搜索
          </el-button>
          <el-button
            @click="handleReset"
            :loading="loading"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 角色表格区域 -->
    <el-card
      class="table-card"
      style="margin-top: 20px;"
    >
      <div
        class="table-header"
        style="margin-bottom: 10px;"
      >
        <el-button
          type="primary"
          @click="handleAddRole"
          style="margin-right: 10px;"
          :loading="loading"
        >
          添加角色
        </el-button>
        <el-button
          type="danger"
          :disabled="disabled"
          @click="handleBatchDelete"
          :loading="loading"
        >
          批量删除
        </el-button>
      </div>

      <el-table
        class="table-content"
        v-loading="loading"
        :data="currentPageRoles"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
        size="small"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column
          type="index"
          label="#"
          width="50"
        />
        <el-table-column
          prop="roleId"
          label="ID"
          width="80"
        />
        <el-table-column
          prop="roleName"
          label="角色名称"
          width="200"
        />
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="200"
        />
        <el-table-column
          prop="updateTime"
          label="更新时间"
          width="200"
        />
        <el-table-column
          label="操作"
          min-width="120"
          fixed="right"
        >
          <template #default="scope">
            <el-button
              size="small"
              @click="handleAssignPermission(scope.row)"
              style="margin-left: 10px;"
              :loading="loading"
            >
              分配权限
            </el-button>
            <el-button
              type="primary"
              size="small"
              @click="handleEditRole(scope.row)"
              style="margin-right: 10px;"
              :loading="loading"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDeleteRole(scope.row.roleId)"
              :loading="loading"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div
        class="pagination-container"
        style="margin-top: 20px; text-align: right;"
      >
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 30]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :size="size"
          :background="background"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑角色对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :before-close="handleDialogClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        label-width="100px"
        style="margin-top: 20px;"
        size="small"
      >
        <el-form-item
          label="角色名称"
          prop="roleName"
        >
          <el-input
            v-model="roleForm.roleName"
            placeholder="请输入角色名称"
            :disabled="loading"
          />
        </el-form-item>

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button
            @click="handleDialogClose"
            :disabled="loading"
          >
            取消
          </el-button>
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="loading"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>


    <!-- 权限分配抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      :title="`权限分配 - ${currentRoleName}`"
      direction="rtl"
      size="50%"
    >
      <div class="permission-drawer-content">
        <el-tree
          :data="visibleMenuRoutes"
          show-checkbox
          node-key="id"
          default-expand-all
          :check-strictly="false"
          :props="{
            children: 'children',
            label: 'label',
            disabled: 'disabled'
          }"
          :default-checked-keys="rolePermissions"
          @check-change="handleCheckChange"
          ref="treeRef"
        />
      </div>
      <div class="permission-drawer-footer">
        <el-button @click="drawerVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="handlePermissionConfirm"
          :loading="loading"
        >确定</el-button>
      </div>
    </el-drawer>

  </div>
</template>

<style scoped>
  .search-card {
    height: 70px;
  }

  .table-header {
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }

  .table-content {
    max-height: calc(100vh - 325px);
    overflow: auto;
  }

  /* 权限分配抽屉样式 */
  .permission-drawer-content {
    padding: 20px;
    max-height: calc(100vh - 200px);
    overflow-y: auto;
  }

  .permission-drawer-footer {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 10px 20px;
    background-color: #fff;
    border-top: 1px solid #eee;
    text-align: right;
  }
</style>